//
//  ConnectionsViewController.m
//  CareWithFriends
//
//  Created by Versatile Systems, Inc on 11/19/13.
//  Copyright (c) 2013 Muludiang. All rights reserved.
//

#import "ConnectionsViewController.h"
#import "FollowingViewController.h"
#import "CWFData.h"

@interface ConnectionsViewController ()

@end

@implementation ConnectionsViewController

@synthesize connectionsTable;
@synthesize refreshControl;

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate *resultPredicate = [NSPredicate
                                    predicateWithFormat:@"first_name contains[cd] %@ OR last_name contains[cd] %@",
                                    searchText , searchText];
    
    searchResults = [tempArray filteredArrayUsingPredicate:resultPredicate];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];

    
    return YES;
}


-(void)searchDisplayController:(UISearchDisplayController *)controller didShowSearchResultsTableView:(UITableView *)tableView{
     tableView.frame = connectionsTable.frame;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
     return [searchResults count];
     
     } else {
     return [tempArray count];
     
     }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"FriendCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
   if (tableView == self.searchDisplayController.searchResultsTableView) {
     cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", [[searchResults objectAtIndex:indexPath.row] valueForKey:@"first_name"],[[searchResults objectAtIndex:indexPath.row] valueForKey:@"last_name"] ];
     } else {
     cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", [[tempArray objectAtIndex:indexPath.row] valueForKey:@"first_name"], [[tempArray objectAtIndex:indexPath.row] valueForKey:@"last_name"]];
     }

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    FollowingViewController *followInvite = [self.storyboard instantiateViewControllerWithIdentifier:@"follow_invite_view"];
    [self.navigationController pushViewController:followInvite animated:YES];
}



-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
[self performSelector:@selector(retunToTop) withObject:nil afterDelay:0.3];
}


-(void)retunToTop{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)refreshTable{
    
    refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Refreshing user list..."];
   
      // custom refresh logic would be placed here...
   
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMM d, h:mm a"];
   NSString *lastUpdated = [NSString stringWithFormat:@"Last updated on %@",
                                  [formatter stringFromDate:[NSDate date]]];
  refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
    [refreshControl endRefreshing];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    //tempArray = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];
    
    tempDict = [NSJSONSerialization JSONObjectWithData:[@"{\"users\":[{\"id\":1350,\"first_name\":\"Kevin\",\"last_name\":\"Colflesh\",\"score\":10,\"role\":\"USER\"},{\"id\":1351,\"first_name\":\"Erik\",\"last_name\":\"Kleinfelder\",\"score\":1,\"role\":\"USER\"},{\"id\":1352,\"first_name\":\"Scott\",\"last_name\":\"Berger\",\"score\":0,\"role\":\"USER\"},{\"id\":1353,\"first_name\":\"Christopher\",\"last_name\":\"Brito\",\"score\":1,\"role\":\"USER\"},{\"id\":1354,\"first_name\":\"Erik\",\"last_name\":\"Kleinfelder\",\"score\":0,\"role\":\"USER\"},{\"id\":1355,\"first_name\":\"Christopher\",\"last_name\":\"Brito\",\"score\":0,\"role\":\"USER\"}]}" dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    
    refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
    [refreshControl setTintColor:[UIColor redColor]];
    [connectionsTable addSubview:refreshControl];
    
    
    
    //NSLog(@"User type: %@", NSStringFromClass([tempDict class]) );
    
    //tempArray = [[NSArray alloc] initWithArray:[tempDict valueForKey:@"users"]];
    //NSLog(@"Users: %d", [tempArray count]);

    CWFData *dataObj = [CWFData sharedInstance];
    //NSLog(@"User list: %@", [dataObj getUsersList]);
    tempArray = [[dataObj getUsersList] valueForKey:@"users"];
    //NSLog(@"Get users: https://cwf.xcal.tv/care-wit-friends/api/v1/users/search?auth_token=%@", [dataObj CWFAuthtoken]);

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
